﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TLM.PlaylistGenerator;
using TLM.VsmdiReader;
using TLM.Wizard.Context;

namespace TLM.Wizard.ViewModels
{
    public class ConversionProgessViewModel : BaseViewModel
    {        
        private bool _migrateToPlaylist;
        private string _playlistPath;
        private bool _migrateToTestCategory;

        private int _conversionProgress;
        private string _resultMessage = string.Empty;

        private BackgroundWorker _backgroundConversionWorker;

        public int ConversionPorgress
        {
            get { return _conversionProgress; }
            set
            {
                if (_conversionProgress != value)
                {
                    _conversionProgress = value;
                    RaisePropertyChanged("ConversionPorgress");
                }
            }
        }

       
        public string ResultMessage
        {
            get { return _resultMessage; }
            set 
            {
                if (_resultMessage != value)
                {
                    _resultMessage = value;
                    RaisePropertyChanged("ResultMessage");
                }                
            }
        }


        private RelayCommand _convertTestListCommand;
        private TestListConversionContext _context;

        public RelayCommand ConvertTestListsCommand 
        { 
            get
            {
                return _convertTestListCommand;
            }
        }

       
        public ConversionProgessViewModel(PlaylistGenerator.Generator playlistGenerator, 
                                          TestCategoryGenerator.Generator testCategoryGenerator,
                                          VsmdiParser vsmdiParser)
        {
            RegisterMessageReceivers();

            _backgroundConversionWorker = new BackgroundWorker();
            _backgroundConversionWorker.WorkerReportsProgress = true;
            _backgroundConversionWorker.DoWork += backgroundConversionWorker_ConvertTestLists;
            _backgroundConversionWorker.ProgressChanged += backgroundConversionWorker_ProgressChanged;
            _backgroundConversionWorker.RunWorkerCompleted += backgroundConversionWorker_ConversionComplete;

            _context = new TestListConversionContext()
                    {
                        VsmdiParser = vsmdiParser,
                        PlaylistGenerator = playlistGenerator,
                        TestCategoryGenerator = testCategoryGenerator
                    };

            _convertTestListCommand = new RelayCommand(StartMigration, () => !this._backgroundConversionWorker.IsBusy);            
        }

        private void StartMigration()
        {
            if (!this._backgroundConversionWorker.IsBusy)
            {
                _backgroundConversionWorker.RunWorkerAsync();
            }
        }

        private void RegisterMessageReceivers()
        {
            Messenger.Default.Register<Messages.ChoiceMessage>
            (
                 this,
                 (message) =>
                 {
                     _migrateToPlaylist = message.MigrateToPlaylist;
                     _migrateToTestCategory = message.MigrateToTestCategory;
                     _playlistPath = message.PlaylistPath;
                 }
            );
        }

        private void backgroundConversionWorker_ConversionComplete(object sender, RunWorkerCompletedEventArgs e)
        {
            this.ResultMessage = "Conversion has been completed.";
        }

        private void backgroundConversionWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e != null)
            {
                this.ConversionPorgress = e.ProgressPercentage;
            }
        }

        private void backgroundConversionWorker_ConvertTestLists(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            if (_context != null)
            {
                VsmdiFile vsmdiFile = null;

                if (_context.VsmdiParser != null)
                {
                    if (_context.VsmdiParser.ValidateVsmdi() == true)
                    {
                        vsmdiFile = _context.VsmdiParser.ParseVsmdiFile();
                    }
                }

                if (_migrateToPlaylist)
                {
                    _context.PlaylistGenerator.CreatePlaylists(vsmdiFile, _playlistPath, AskOverwriteFile);
                }

                if (_migrateToTestCategory)
                {
                    _context.TestCategoryGenerator.AddTestCategories(vsmdiFile);
                }
            }

            
        }

        private bool AskOverwriteFile(string filename)
        {   
            var comfirmResult = MessageBox.Show(String.Format(CultureInfo.InvariantCulture, "The file {0} already exists. Do you want to replace it?", filename),
                                                                           "File already exists",
                                                                           MessageBoxButtons.YesNo,
                                                                           MessageBoxIcon.Question,
                                                                           MessageBoxDefaultButton.Button1,
                                                                           MessageBoxOptions.DefaultDesktopOnly
                                                                           );
            if (comfirmResult == DialogResult.Yes)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
